<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/8/6 02:01
 */

namespace App\Project\Traits\Model;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;

trait WhereTimeBetween
{
    protected function getTimeField()
    {
        if (property_exists('between_time_field', $this)) {
            return $this->between_time_field;
        }

        return "{$this->getTable()}.time";
    }

    /**
     * @param \Illuminate\Database\Eloquent\Builder $builder
     * @param null                                  $times
     * @return $this|\Illuminate\Database\Eloquent\Builder
     */
    public function scopeWhereTimeBetween(Builder $builder, $times = null)
    {
        if (empty($times))
            return $builder;

        $field = $this->getTimeField();

        if (is_string($times)) {
            if (false === strpos($times, ',')) {

                return $builder->where($field, '=', $times);
            } else {
                $times = explode(',', $times);
            }
        }

        list($start, $end) = $times;

        if ($start && $end) {
            return $builder->whereBetween($field, $times);
        } elseif ($start) {
            return $builder->where($field, '>=', $start);
        } elseif ($end) {
            return $builder->where($field, '<=', $end);
        }

        return $builder;
    }
}